<template>
    <div v-loading="loading" style="width: 100%">
        <SavePage :title="pageDisabled ? `${form.taskNumber}-记录结果` : `${titleMap[form.type]}巡查记录表`">
            <template v-if="pageDisabled" slot="title">
                <span>巡查类型：{{ titleMap[form.type] }}巡查</span>
            </template>
            <template slot="buttons">
                <BaseButton :disabled="imageUploadOver" :loading="submitLoading" @click="handleSubmit">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips v-if="pageDisabled" :title="`${titleMap[form.type]}巡查记录表`" :required="true" />
                <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="88px">
                    <el-row :gutter="24">
                        
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="路线名称" prop="highwayCode">
                                <RoadSelect
                                    :value.sync="form.highwayCode"
                                    :name.sync="form.highwayName"
                                    :stake.sync="form.stake"
                                    :disabled="pageDisabled"
                                    clearable
                                />
                                <div v-show="form.highwayCode" class="stake-tip">桩号范围：{{ form.stake }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="12" :lg="16">
                            <el-col :span="7" style="padding: 0">
                                <el-form-item label="检查路段" prop="startStake1">
                                    <el-input
                                        v-model.trim="form.startStake1"
                                        :placeholder="!form.highwayCode || pageDisabled ? '请选择路线' : '请输入'"
                                        maxlength="3"
                                        :disabled="!form.highwayCode || pageDisabled"
                                        @change="form.endStake1 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="endStake1"
                                    :rules="useCheckStake(form.highwayCode, 1, form.startStake1, form.stake)"
                                >
                                    <el-input v-model.trim="form.endStake1" :disabled="!form.startStake1 || pageDisabled" maxlength="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="7" style="padding: 0">
                                <el-form-item class="spe-item" label-width="50px" label="~" prop="startStake2">
                                    <el-input
                                        v-model.trim="form.startStake2"
                                        :disabled="!form.highwayCode || pageDisabled"
                                        :placeholder="!form.highwayCode || pageDisabled ? '请选择路线' : '请输入'"
                                        maxlength="3"
                                        @change="form.endStake2 = ''"
                                    >
                                        <div slot="prepend" class="input-unit">K</div>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5" style="padding: 0">
                                <el-form-item
                                    class="spe-item"
                                    label-width="30px"
                                    label="+"
                                    prop="endStake2"
                                    :rules="useCheckStake(form.highwayCode, 1, form.startStake2, form.stake)"
                                >
                                    <el-input v-model.trim="form.endStake2" :disabled="!form.startStake2 || pageDisabled" maxlength="3" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="巡查日期" prop="inspectDate">
                                <el-date-picker
                                    v-model="form.inspectDate"
                                    type="date"
                                    placeholder="请选择"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="巡查时段" prop="time" style="height: 32px;">
                                <el-time-picker
                                    v-model="form.time"
                                    is-range
                                    size="small"
                                    format="HH:mm"
                                    value-format="HH:mm"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    style="width: 100%;"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="天气" prop="whether">
                                <el-select v-model="form.whether" clearable placeholder="请选择" style="width: 100%">
                                    <el-option v-for="item in weather" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="检查部门" prop="deptIds">
                                <OrgSelect :is-filter="true" :value.sync="form.deptIds" :name.sync="form.deptName" :disabled="pageDisabled" @change="form.inspectUsers = []" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="巡查人员" prop="inspectUsers">
                                <UserSelect :id="deptId" :multiple="true" :value.sync="form.inspectUsers"></UserSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="负责人" prop="principal">
                                <UserSelect :is-all="true" :value.sync="form.principal"></UserSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="车载行车记录仪编号" label-width="146px" prop="dashcamNum">
                                <el-input v-model.trim="form.dashcamNum" maxlength="50" show-word-limit clearable placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="16">
                            <el-form-item label="备注">
                                <el-input v-model.trim="form.remark" type="textarea" autosize maxlength="200" show-word-limit clearable placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="巡查过程记录" prop="inspectProcessRecord">
                                <el-input v-model.trim="form.inspectProcessRecord" type="textarea" rows="3" maxlength="500" show-word-limit clearable placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="上传图片">
                                <ImageUploadNew ref="imageUpload" :list.sync="photos" :over.sync="imageUploadOver"></ImageUploadNew>
                            </el-form-item>
                        </el-col>
                        <el-col v-for="(item, index) in photos" :key="item.uid" :span="24">
                            <el-form-item :label="`图片${index+1}说明`">
                               <el-input v-model.trim="photos[index].picDesc" maxlength="100" show-word-limit clearable placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <BaseTable :columns="columns" :data="tableList">
                    <template #direction="{ scope: { row } }">
                        <el-select v-model="row.direction" size="mini" clearable placeholder="请选择" style="width: 100%">
                            <el-option v-for="m in directionOptions" :key="m.value" :label="m.label" :value="m.value" />
                        </el-select>
                    </template>
                    <template #locationType="{ scope: { row } }">
                        <el-select v-model="row.locationType" size="mini" :disabled="!form.highwayCode" clearable placeholder="请选择" style="width: 100%" @change="locationTypeChange(row)">
                            <el-option v-for="m in locationOptions" :key="m.value" :label="m.label" :value="m.value" />
                        </el-select>
                    </template>
                    <template #location="{ scope: { row, $index } }">
                        <div v-if="!row.locationType">
                            <el-input placeholder="请先选择位置类型" disabled></el-input>
                        </div>
                        <!-- 设施 -->
                        <div v-if="row.locationType === 1">
                            <NewFacilitySelect
                                :value.sync="row.facilityCode"
                                :params="{ roadCode: form.highwayCode, direction: row.direction }"
                                :name.sync="row.facilityName"
                                :lng-lat.sync="row.lngLatList"
                                clearable
                            />
                        </div>
                        <!-- 桩号 -->
                        <div v-if="row.locationType === 2" class="stake">
                            <el-input v-model.trim="row.stake1" placeholder="请输入" maxlength="3" @change="$set(row, 'stake2', '')">
                                <div slot="prepend" class="input-unit">K</div>
                            </el-input>
                            <div class="plus">+</div>
                            <el-input
                                v-model.trim="row.stake2"
                                :disabled="!row.stake1"
                                maxlength="3"
                                placeholder="请输入"
                                @blur="handleValidate(row.stake1, row.stake2, row)"
                            />
                        </div>
                        <!-- 桩号范围 -->
                        <div v-if="row.locationType === 3" class="stake">
                            <el-input v-model.trim="row.startStake1" placeholder="起点" maxlength="3" @change="$set(row, 'endStake1', '')">
                                <div slot="prepend" class="input-unit">K</div>
                            </el-input>
                            <div class="plus">+</div>
                            <el-input
                                v-model.trim="row.endStake1"
                                maxlength="3"
                                placeholder="请输入"
                                :disabled="!row.startStake1"
                                @blur="handleValidate(row.startStake1, row.endStake1, row)"
                            />
                        </div>
                        <div v-if="row.locationType === 3" class="stake">
                            <el-input v-model.trim="row.startStake2" placeholder="终点" maxlength="3" @change="$set(row, 'endStake2', '')">
                                <div slot="prepend" class="input-unit">K</div>
                            </el-input>
                            <div class="plus">+</div>
                            <el-input
                                v-model.trim="row.endStake2"
                                maxlength="3"
                                placeholder="请输入"
                                :disabled="!row.startStake2"
                                @blur="handleValidate(row.startStake2, row.endStake2, row)"
                            />
                        </div>
                        <div v-if="row.locationType === 4" class="device" @click="handleSelectDevice($index)">
                            <i class="el-icon-arrow-down device-icon"></i>
                            <div v-if="row.deviceList.length === 0" class="placeholder">请选择</div>
                            <div v-else class="color-blue">
                                <BaseTooltips :text="row.deviceListName" class-name="g-line-1" />
                            </div>
                        </div>
                    </template>
                    <template #type="{ scope: { row } }">
                        <!-- <el-input v-model.trim="row.type" maxlength="8" clearable placeholder="请输入" /> -->
                        <el-select v-model="row.type" :disabled="!row.locationType || row.locationType === 4" clearable size="mini" placeholder="请选择" style="width: 100%">
                            <el-option v-for="m in ReportTypeOptions" :key="m.value" :label="m.label" :value="m.label" />
                        </el-select>
                    </template>
                    <template #description="{ scope: { row } }">
                        <el-input v-model.trim="row.description" type="textarea" autosize maxlength="200" show-word-limit clearable placeholder="请输入" />
                    </template>
                    <template #unit="{ scope: { row } }">
                        <el-input v-model.trim="row.unit" maxlength="8" clearable placeholder="请输入" />
                    </template>
                    <template #num="{ scope: { row } }">
                        <el-input
                            v-model.trim="row.num"
                            type="number"
                            oninput="if(value.length > 8) value = value.slice(0, 8)"
                            clearable
                            placeholder="请输入"
                        />
                    </template>
                    <template #disposalResults="{ scope: { row } }">
                        <el-input v-model.trim="row.disposalResults" type="textarea" autosize maxlength="300" show-word-limit placeholder="请输入" class="spe-input" />
                    </template>
                    <template #handle="{ scope: { $index } }">
                        <BaseButton v-if="$index === tableList.length - 1" type="text" @click="handleAdd">添加行</BaseButton>
                        <BaseButton type="text" :disabled="tableList.length === 1" color="danger" @click="handleDelete($index)">删除</BaseButton>
                    </template>
                </BaseTable>
            </template>
        </SavePage>

        <!-- 选择设备弹框表格 -->
        <el-dialog width="860px" :visible.sync="deviceDialogVisible" title="选择设备">
            <DeviceDialog
                :visible="deviceDialogVisible"
                :params="{ highwayCode: form.highwayCode }"
                @close="deviceDialogVisible = false"
                @get-list="getDeviceList"
            />
        </el-dialog>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { LocationOptions, ReportTypeOptions } from '@/views/maintenance-decision/constants'
import { DirectionTwoWayOptions } from '@/config/constants'
import { InspectionRecordModel } from '@/models'
import reconfirm from '@/utils/reconfirm'
import useCheckStake from '@/hooks/useCheckStake'
import { isInteger } from '@/utils/validate'

// 日常缺陷表格项
const dailyColumns = [
    {
        attrs: {
            prop: 'number',
            label: '序号',
            width: '70',
            type: 'index'
        }
    },
    {
        slot: 'direction',
        attrs: {
            prop: 'direction',
            label: '方向',
            width: '130'
        }
    },
    {
        slot: 'locationType',
        attrs: {
            prop: 'locationType',
            label: '位置类型',
            width: '140'
        }
    },
    {
        slot: 'location',
        attrs: {
            prop: 'location',
            label: '位置桩号',
            width: '230'
        }
    },
    {
        slot: 'type',
        attrs: {
            prop: 'type',
            label: '上报类型',
            width: '140'
        }
    },
    {
        slot: 'description',
        attrs: {
            prop: 'description',
            label: '事件/问题描述',
            'min-width': '170'
        }
    },
    {
        slot: 'unit',
        attrs: {
            prop: 'unit',
            label: '单位',
            width: '130',
            'show-overflow-tooltip': true
        }
    },
    {
        slot: 'num',
        attrs: {
            prop: 'num',
            label: '数量',
            width: '130',
            'show-overflow-tooltip': true
        }
    },
    {
        slot: 'disposalResults',
        attrs: {
            prop: 'disposalResults',
            label: '处置结果',
            'min-width': '170'
        }
    },
    {
        slot: 'handle',
        attrs: {
            label: '操作',
            width: '140'
        }
    }
]

// 夜间缺陷表格项
const nightColumns = [
    {
        attrs: {
            prop: 'number',
            label: '序号',
            width: '70',
            type: 'index'
        }
    },
    {
        slot: 'direction',
        attrs: {
            prop: 'direction',
            label: '方向',
            width: '130'
        }
    },
    {
        slot: 'locationType',
        attrs: {
            prop: 'locationType',
            label: '位置类型',
            width: '170'
        }
    },
    {
        slot: 'location',
        attrs: {
            prop: 'location',
            label: '位置桩号',
            width: '240'
        }
    },
    {
        slot: 'type',
        attrs: {
            prop: 'type',
            label: '上报类型',
            width: '170'
        }
    },
    {
        slot: 'description',
        attrs: {
            prop: 'description',
            label: '事件/问题描述',
            'min-width': '170'
        }
    },
    {
        slot: 'disposalResults',
        attrs: {
            prop: 'disposalResults',
            label: '处置结果',
            'min-width': '170'
        }
    },
    {
        slot: 'handle',
        attrs: {
            label: '操作',
            width: '140'
        }
    }
]

export default {
    name: 'AddDailyNightTask',
    data() {
        return {
            ReportTypeOptions,
            titleMap: {
                1: '日常',
                2: '夜间'
            },
            model: new InspectionRecordModel(),
            loading: false,
            submitLoading: false,
            form: {
                deptIds: [],
                // time: [], 不加默认值，会导致选中框卡顿
                inspectUsers: [],
                startStake1: '',
                startStake2: '',
                endStake1: '',
                endStake2: '',
                photos: []
            },
            rules: {
                deptIds: [{ required: true, message: '请选择检查部门', trigger: 'change' }],
                highwayCode: [{ required: true, message: '请选择路线名称', trigger: 'change' }],
                startStake1: [
                    { required: true, message: '请输入起始桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                startStake2: [
                    { required: true, message: '请输入终点桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                inspectDate: [{ required: true, message: '请选择巡查日期', trigger: 'change' }],
                time: [{ required: true, message: '请选择巡查时段', trigger: 'change' }],
                whether: [{ required: true, message: '请选择天气', trigger: 'change' }],
                inspectUsers: [{ required: true, message: '请选择巡查人员', trigger: 'change' }],
                principal: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                // dashcamNum: [{ required: true, message: '请输入车载行车记录仪编号', trigger: 'blur' }],
                inspectProcessRecord: [{ required: true, message: '请输入巡查过程记录', trigger: 'blur' }],
            },
            locationOptions: LocationOptions,
            directionOptions: DirectionTwoWayOptions,
            tableList: [
                {
                    locationType: '',
                    facilityName: '',
                    location: '',
                    type: '',
                    description: '',
                    unit: '',
                    num: '',
                    disposalResults: '',
                    deviceList: []
                }
            ],
            columns: [],
            imageUploadOver: false,
            deviceDialogVisible: false,
            currentIndex: 0,
            photos: []
        }
    },
    computed: {
        ...mapState('types', ['weather']),
        deptId() {
            if (Array.isArray(this.form.deptIds)) {
                return this.form.deptIds[this.form.deptIds.length - 1]
            }
            return this.form.deptIds
        },
        pageDisabled() {
            return !(this.$route.query.pageType === 'record')
        },
        params() {
            const params = {
                roadCode: this.form.highwayCode,
            }
            return params
        },
    },
    created() {
        this.$store.dispatch('types/query', 'weather')
        // 合并url上传递的参数
        const query = this.$route.query
        // 巡查任务里填写结果时，需要回填部门，保证数据统一处理为数组。常规情况下回填默认当前人员的所在部门，部门只有当前id，用数组不能正常回显，要用number
        query.deptIds = query.deptIds ? query.deptIds.toString().split(',').map(Number) : this.$store.getters.avatar.depart[0].id
        query.type = Number(query.type)
        this.form = Object.assign(this.form, query)
        // 根据类型修改日常和夜间缺陷表格的表头配置项
        if (this.form.type === 1) {
            this.columns = dailyColumns
        } else if (this.form.type === 2) {
            this.columns = nightColumns
        }
    },
    methods: {
        locationTypeChange(row) {
            if (row.locationType === 4) {
                // row.type === '机电故障'
                console.log(row)
                this.$set(row, 'type', '机电故障')
            }
        },
        handleValidate(stake1, stake2, row) {
            // 把桩号转为具体的数字，K是千米桩号
            const smallStake = this.form.startStake1 * 1000 + Number(this.form.endStake1)
            const bigStake = this.form.startStake2 * 1000 + Number(this.form.endStake2)
            const stake = stake1 * 1000 + Number(stake2)
            if (stake < smallStake || stake > bigStake) {
                row.validate = false
                this.$message.error('位置桩号超出检查路段范围！')
            } else {
                row.validate = true
            }
            console.log(smallStake, bigStake, stake)
        },
        handleAdd() {
            this.tableList.push({
                direction: '',
                locationType: '',
                location: '',
                type: '',
                description: '',
                unit: '',
                num: '',
                disposalResults: '',
                deviceList: []
            })
        },
        handleDelete(index) {
            reconfirm({
                isPromise: false,
                callback: () => {
                    this.tableList.splice(index, 1)
                }
            })
        },
        handleSubmit() {
            this.submitLoading = true
            // 获取图片拼接的url字符串
            const photosArray = this.photos.map(item => {
                return {
                    picName: item.name,
                    url: item.response.data.objectUrl,
                    picDesc: item.picDesc
                }
            })
            this.$refs.form.validate((valida) => {
                if (valida) {
                    const tableValidate = !this.tableList.some((item) => item.validate === false)
                    if (!tableValidate) {
                        this.$message.error('缺陷中位置桩号超出检查路段范围！')
                        this.submitLoading = false
                        return
                    }
                    const tableListValidateRes = this.tableListValidate()
                    if (tableListValidateRes) {
                        this.$message.error('缺陷中事件/问题描述不能为空！')
                        this.submitLoading = false
                        return
                    }
                    // 获取图片拼接的url字符串
                    const photosArray = this.photos.map(item => {
                        return {
                            picName: item.name,
                            url: item.response.data.objectUrl,
                            picDesc: item.picDesc
                        }
                    })
                    console.log(photosArray)
                    // 获取表格里填写的缺陷
                    const content = this.formatTableData()
                    const data = {
                        ...this.form,
                        deptIds: this.form.deptIds.toString(),
                        inspectUsers: this.form.inspectUsers.toString(),
                        inspectTime: this.form.time.join('~'),
                        resultContent: [{ photosArray, content }]
                    }
                    this.model
                        .saveOrUpdate(data)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                } else {
                    this.submitLoading = false
                }
            })
        },
        tableListValidate() {
            const list = []
            this.tableList.forEach((item) => {
                const hasValue = Object.values(item).some((m) => {
                    if (Array.isArray(m)) {
                        if (m.length > 0) {
                            return true
                        } else {
                            return false
                        }
                    } else if (Object.prototype.toString.call(m) === '[object Object]') {
                        if (Object.keys.length > 0) {
                            return true
                        } else {
                            return false
                        }
                    } else {
                        return !!m
                    }
                })
                if (hasValue) {
                    if (item.description) {
                        list.push(true)
                    } else {
                        list.push(false)
                    }
                } else {
                    list.push(true)
                }
            })
            const res = list.some((item) => item === false)
            return res
        },
        formatTableData() {
            const content = this.tableList.map((item) => {
                let location = ''
                let locationCode = ''
                switch (item.locationType) {
                    case 1:
                        location = item.facilityName
                        // code用于回填
                        locationCode = item.facilityCode ? item.facilityCode.toString() : ''
                        break
                    case 2:
                        location = `K${item.stake1}+${item.stake2}`
                        break
                    case 3:
                        location = `K${item.startStake1}+${item.endStake1}~K${item.startStake2}+${item.endStake2}`
                        break
                    case 4:
                        location = item.deviceList.map((m) => m.name).toString()
                        locationCode = item.deviceList.map((m) => m.number).toString()
                        break
                    default:
                        location = ''
                        break
                }
                return {
                    ...item,
                    location,
                    locationCode
                }
            })

            console.log(content)
            return content
        },
        handleSelectDevice(index) {
            // 当前点击选择机电的数据下标
            this.currentIndex = index
            this.deviceDialogVisible = true
        },
        getDeviceList(value) {
            this.tableList[this.currentIndex].deviceList = value
            this.tableList[this.currentIndex].deviceListName = value.map((item) => item.name).join('；')
        },
        validNum(rule, value, callback) {
            if (value && !isInteger(value)) {
                callback(new Error('请输入数字'))
            } else {
                callback()
            }
        },
        useCheckStake
    }
}
</script>
<style lang="scss" scoped>

.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}
.spe-input {
    ::v-deep {
        .el-input__inner {
            padding-right: 50px;
        }
    }
}
.device {
    min-width: 100px;
    height: 32px;
    padding: 0 20px 0 5px;
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    position: relative;
    color: #d2d2d2;
    cursor: pointer;
    .placeholder {
        padding-left: 15px;
    }
    .device-icon {
        font-size: 14px;
        position: absolute;
        right: 5px;
        top: 8px;
    }
}
.stake {
    display: flex;
    ::v-deep {
        .el-input {
            min-width: auto !important;
        }
        .el-input__inner {
            width: 60px;
            padding: 0 6px;
            min-width: auto !important;
        }
        .el-input-group__prepend {
            padding: 0 10px;
        }
    }
    .plus {
        margin: 0 12px;
    }
}
.stake + .stake {
    margin-top: 6px;
}
</style>
